using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class KMenu : MonoBehaviour {
	
	public KinectMenuItem Item;
    public string Path = "Resources";
    public string SearchPattern = "*.jpg";
	
	List<Transform> items = new List<Transform>();
	
	void Start () {
		
		float x = -4;
		float z = 0;
				
		// Load images to a grid dynamically
		foreach (string filename in System.IO.Directory.GetFiles(Path, SearchPattern)) {
            
			// If one 3x3 grid is full add padding before another grid.
			int factor = items.Count / 9;
			
			KinectMenuItem newItem = Instantiate(Item) as KinectMenuItem;
            newItem.Init(filename);
			
			Vector3 pos = new Vector3(x + 5 * factor,-0.5f,z);
			newItem.transform.position = pos;
			
			z+=4;
			if (z > 8) {
				x+=4;
				z = 0;
			}
			
            AddItem(newItem.transform);
        }
		
		BroadcastMessage("SetSwipesAllowed", items.Count / 9, SendMessageOptions.DontRequireReceiver);
		
		foreach (Transform child in transform) {
			AddRigidbodyToMenuObject(child.gameObject);
		}
	}
	
	public void AddItem(Transform item) {
		item.parent = this.transform;
        items.Add(item);
    }
	
	private void AddRigidbodyToMenuObject(GameObject obj) {
		
		obj.AddComponent<Rigidbody>();
		Rigidbody r = obj.rigidbody;
		
		r.mass = 1;
		r.drag = 0;
		r.angularDrag = 0;
		r.useGravity = false;
		r.isKinematic = false;
		r.interpolation = RigidbodyInterpolation.None;
		r.collisionDetectionMode = CollisionDetectionMode.Discrete;
		r.constraints = RigidbodyConstraints.FreezeAll;	
	}
	
	void OnGUI() {
		if (Event.current.Equals(Event.KeyboardEvent("escape"))) {
            print("Quitting");
            Application.Quit();
        }
	}
}